﻿using ConfExpert.Forms.Aksesuar;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPivotGrid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Aksesuar
{
    //TODO K.A tüm renkler yerine seçilen pivot satırlarının aksesuarlarını değiştir!

    public partial class AksSeriRenkleDegisen : XForm
    {
        DataSet dsx;
        BindingSource bs;
        string Idxs, Customer;
        public AksSeriRenkleDegisen(string idxs, string Customer)
        {
            InitializeComponent();
            Idxs = idxs;
            this.Customer = Customer;//Texcomm ya da WB olmasına göre SP isimlerini değiştiriyorum
        }

        private void AksSeriRenkleDegisen_Load(object sender, EventArgs e)
        {

            dsx = ExecuteDataSet("GetRenkleDegisen" + Customer, Idxs);
            bs = gridView1.Init(dsx.Tables[0]);
            gridControl1.DataSource = null;

            gvMyTreeLines.Init(dsx.Tables[2].Clone());
            gvMyTreeLines.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            gleProductCategory.Edit.Assign(RI(Rp.ProductCategory));
            ((RepositoryItemGridLookUpEdit)gleProductCategory.Edit).TextEditStyle = TextEditStyles.DisableTextEditor;
            gridView1.OptionsBehavior.Editable = false;

            gridView1.MakeColumnInvisible("ProductId");

            InitPivot(pvg, bs);

            gvMyTreeLines.Columns["Qty"].Caption = "Adet";
            gvMyTreeLines.Columns["Qty"].DisplayFormat.FormatString = "#,##0.###";


            gridView1.Columns["Qty"].Caption = "Adet";
            gridView1.Columns["Qty"].DisplayFormat.FormatString = "#,##0.###";

            btnSil.ItemClick += btnSil_ItemClick;
            btnKaydetKapat.ItemClick += btnKaydetKapat_ItemClick;
            btnKaydet.ItemClick += btnKaydet_ItemClick;

            //splitContainerControl1.AutoSize();
            splitContainerControl2.SizeChanged += MySizeChanged2;
            splitContainerControl1.AutoSize();

            btnSil.Enabled = false;
            gleProductCategory.EditValueChanged += gleProductCategory_EditValueChanged;

            emptyEditor = new RepositoryItemButtonEdit();
            emptyEditor.Buttons.Clear();
            emptyEditor.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            gcMyTreeLines.RepositoryItems.Add(emptyEditor);

            bbiAksesuarEkle.ItemClick += bbiAksesuarEkle_ItemClick;
            gvMyTreeLines.ShowingEditor += gvMyTreeLines_ShowingEditor;
            gvMyTreeLines.CustomRowCellEdit += gvMyTreeLines_CustomRowCellEdit;
            gvMyTreeLines.GetManager().Pasting += AksSeriRenkleDegisen_Pasting;

            pgc_FocusedCellChanged(null, null);

            this.Shown += AksSeriRenkleDegisen_Shown;
        }

        void AksSeriRenkleDegisen_Pasting(int rowHandle, DevExpress.XtraGrid.Columns.GridColumn column, object val, System.ComponentModel.CancelEventArgs ce)
        {
            if (rowHandle < 0)
                return;
            if (column.FieldName == "Qty" && val.ToStr() != "")
            {
                DataTable dtZorunluAdet = dsx.Tables[3];
                int ProductCategoryId = gvMyTreeLines.GetRowCellValue(rowHandle, "ProductCategoryId").ToInt();
                int AksesuarId = gvMyTreeLines.GetRowCellValue(rowHandle, "AksesuarId").ToInt();

                bool IsProductCategoryExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId).Length > 0;
                bool IsOptionExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId + " and Isnull(Qty,0) = " + val.ToStr().Replace(",", ".")).Length > 0;

                ce.Cancel = (IsProductCategoryExist && !IsOptionExist) || AksesuarId == 0;
            }
        }
        void gvMyTreeLines_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.Column.FieldName == "Seri" &&
                view.GetRowCellDisplayText(e.RowHandle, "AksSeriId") == string.Empty)
                e.RepositoryItem = emptyEditor;

            else if (e.Column.FieldName == "Qty")
            {
                DataTable dtZorunluAdet = dsx.Tables[3];
                int ProductCategoryId = view.GetRowCellValue(e.RowHandle, "ProductCategoryId").ToInt();
                bool IsProductCategoryExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId).Length > 0;
                if (IsProductCategoryExist)
                {
                    List<string> adet = new List<string>();
                    foreach (DataRow dr in dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId))
                        adet.Add(dr["Qty"].ToDecimal().ToString("#,##0.###"));

                    RepositoryItemComboBox riAdet = new RepositoryItemComboBox();
                    riAdet.Items.AddRange(adet);
                    riAdet.TextEditStyle = TextEditStyles.DisableTextEditor;
                    e.RepositoryItem = riAdet;
                }
            }
        }

        void gvMyTreeLines_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            GridView view = sender as GridView;

            int AksesuarId = view.GetRowCellValue(view.FocusedRowHandle, "AksesuarId").ToInt();
            e.Cancel = view.FocusedColumn.FieldName == "Qty" && AksesuarId == 0;
        }

        void bbiAksesuarEkle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (AksesuarSec aks = new AksesuarSec())
                if (aks.ShowDialog() == DialogResult.OK)
                {
                    DataTable dtAksesuar = aks.DtAksesuar;

                    foreach (DataRow drAksesuar in dtAksesuar.Rows)
                    {
                        DataRow dr = gvMyTreeLines.DataTable().NewRow();

                        dr["AksesuarId"] = drAksesuar["AksesuarId"];
                        dr["Qty"] = drAksesuar["Adet"];

                        gvMyTreeLines.DataTable().Rows.Add(dr);
                    }
                }
        }

        void AksSeriRenkleDegisen_Shown(object sender, EventArgs e)
        {
            pvg.Cells.Selection = new Rectangle(0, 0, 1, pvg.Cells.RowCount);
            gvMyTreeLines.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gvMyTreeLines.FocusedColumn = gvMyTreeLines.Columns["AksesuarId"];
            gvMyTreeLines.ShowEditor();
        }


        RepositoryItemButtonEdit emptyEditor;

        void gleProductCategory_EditValueChanged(object sender, EventArgs e)
        {
            btnSil.Enabled = (gleProductCategory.EditValue.ToInt() > 0);
        }

        void btnSil_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bs.DataSource = ExecuteDataSet("DeleteRenkleDegisen" + Customer, Idxs, GetRows(), gleProductCategory.EditValue.ToInt());
            //gvYeni.RefreshData();
            pvg.BestFit();
        }

        void MySizeChanged2(object sender, EventArgs e)
        {
            SplitContainerControl scc = sender as SplitContainerControl;
            scc.SizeChanged -= MySizeChanged2;
            scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) * 3 / 4;
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Kaydet();
        }

        private void Kaydet()
        {
            gvMyTreeLines.EndEditing();
            DataTable dt = gvMyTreeLines.DataTable();

            int LenEmptyQty = dt.Select("Isnull(Qty,0) = 0").Length;

            if (LenEmptyQty > 0)
                throw new ApplicationException("Adet boş bırakılamaz !");

            string xml = dt.Serialize();
            bs.DataSource = ExecuteDataSet("UpdRenkleDegisen" + Customer, Idxs, GetRows(), xml);
            DataTable dtx = gvMyTreeLines.DataTable();
            dtx.Clear();
            //gvYeni.RefreshData();
            pvg.BestFit();
        }

        void btnKaydetKapat_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Kaydet();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        string GetRows()
        {
            List<PivotCellEventArgs> selectedCells = new List<PivotCellEventArgs>();
            foreach (Point pt in pvg.Cells.MultiSelection.SelectedCells)
            {
                for (int cl = 0; cl < pvg.Cells.ColumnCount; cl++)
                {
                    PivotCellEventArgs cellInfo = pvg.Cells.GetCellInfo(cl, pt.Y);
                    selectedCells.Add(cellInfo);
                }

            }

            for (int cl = 0; cl < pvg.Cells.ColumnCount; cl++)
            {
                PivotCellEventArgs cellInfo = pvg.Cells.GetCellInfo(cl, pvg.Cells.GetFocusedCellInfo().RowIndex);
                selectedCells.Add(cellInfo);
            }

            //selectedCells.Add(pvg.Cells.GetFocusedCellInfo());

            List<int> selectedRows = new List<int>();
            foreach (PivotCellEventArgs ci in selectedCells)
            {
                PivotDrillDownDataSource dataSource = ci.CreateDrillDownDataSource();
                for (int i = 0; i < dataSource.RowCount; i++)
                    if (!selectedRows.Contains((int)dataSource[i]["idx"]))
                        selectedRows.Add((int)dataSource[i]["idx"]);
            }
            return string.Join<int>(",", selectedRows);
        }

        private string GetAksesuarIds()
        {
            string idxs = string.Empty;
            for (int i = 0; i < gvMyTreeLines.DataRowCount; i++)
                idxs += gvMyTreeLines.GetRowCellValue(i, "AksesuarId").ToString() + ",";

            if (idxs.Substring(idxs.Length - 1, 1) == ",")
                idxs = idxs.Substring(0, idxs.Length - 1);
            return idxs;
        }

        void pivotGridControl1_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            if (e.Focused)
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
        }

        ImageList imageList1;
        bool PivotInitialized = false;
        void InitPivot(PivotGridControl pgc, BindingSource bs)
        {
            pgc.DataSource = bs;

            if (!PivotInitialized)
            {
                imageList1 = new ImageList();
                imageList1.ImageSize = new Size(32, 32);
                imageList1.ColorDepth = ColorDepth.Depth16Bit;
                imageList1.Images.Add("0", notready);

                foreach (DataRow dr in dsx.Tables[1].Rows)
                    if (dr["ProductId"].ToInt() > 0)
                        if (!AppSession.Lookups.V_Kumas.FindByProductId(dr["ProductId"].ToInt(-1)).IsPhotoMikroNull())
                            imageList1.Images.Add(dr["ProductId"].ToString(), ConvertByteArrayToImage(AppSession.Lookups.V_Kumas.FindByProductId((int)dr["ProductId"]).PhotoMikro));

                pgc.ValueImages = imageList1;
                pgc.FieldValueImageIndex += pgc_FieldValueImageIndex;
                pgc.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
                pgc.CellClick += new PivotCellEventHandler(pivotGridControl1_CellClick);
                pgc.FocusedCellChanged += pgc_FocusedCellChanged;
                pgc.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
                pgc.CustomAppearance += new PivotCustomAppearanceEventHandler(pivotGridControl1_CustomAppearance);


                pgc.BeginUpdate();

                //new field - toplam tutar  (metre x fiyat+dvz cinsi)

                //AddNewField(pgc, "DosyaNo", PivotArea.FilterArea);
                //AddNewField(pgc, "CodCliente", PivotArea.FilterArea);
                //AddNewField(pgc, "Linea", PivotArea.FilterArea);
                /*
                PivotGridFieldBase[] pgf1 = new PivotGridFieldBase[3];
                pgf1[0] = AddNewField(pgc, "Linea", PivotArea.RowArea);
                pgf1[1] = AddNewField(pgc, "Modello", PivotArea.RowArea);
                pgf1[1].ExpandedInFieldsGroup = false;
                pgf1[2] = AddNewField(pgc, "Tex", PivotArea.RowArea);
                pgc.Groups.Add(pgf1, "ModelloTex");
                */

                //PivotGridField qa = AddNewField(pgc, "QtyAvailable", PivotArea.RowArea);
                //qa.ValueFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                //qa.ValueFormat.FormatString = "#,###.0";
                //qa.Appearance.Value.Options.UseTextOptions = true;
                //qa.Appearance.Value.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;

                AddNewField(pgc, "Art", PivotArea.RowArea);
                AddNewField(pgc, "ProductId", PivotArea.RowArea).FieldEdit = RI(Rp.V_Kumas);
                AddNewField(pgc, "idx", PivotArea.RowArea).Visible = false;
                AddNewField(pgc, "ProductCategoryId", PivotArea.ColumnArea).FieldEdit = RI(Rp.ProductCategory);

                AddNewField(pgc, "Qty", PivotArea.DataArea);


                //.Width = 40;  .Visible = true;
                //    fld.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;

                //foreach (PivotGridField pgf in pgc.Fields)
                //{
                //    pgf.SortOrder = PivotSortOrder.Ascending;
                //    pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
                //}
                pgc.EndUpdate();

                PivotInitialized = true;
            }
            pgc.BestFit();
        }

        void pgc_FocusedCellChanged(object sender, EventArgs e)
        {
            gridControl1.DataSource = pvg.Cells.GetFocusedCellInfo().CreateDrillDownDataSource();//e.CreateDrillDownDataSource();
            gridView1.MakeColumnInvisible("Scan", "ProductId", "Art");
            ExpandCollapse(splitContainerControl1, (gvMyTreeLines.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));
            gridView1.BestFitColumns();
            gridView1.MoveFirst();
        }


        void pgc_FieldValueImageIndex(object sender, PivotFieldImageIndexEventArgs e)
        {
            if (e.Field != null)
                if (e.Field.FieldName == "ProductId")
                    if (e.Value != null)
                    {
                        if (imageList1.Images.ContainsKey(e.Value.ToString()))
                            e.ImageIndex = imageList1.Images.IndexOfKey(e.Value.ToString());
                    }
                    else
                        e.ImageIndex = 0;
        }


        void pivotGridControl1_CellClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            gridControl1.DataSource = e.CreateDrillDownDataSource();
            gridView1.MakeColumnInvisible("Scan", "ProductId", "Art");
            ExpandCollapse(splitContainerControl1, (gvMyTreeLines.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));
            gridView1.BestFitColumns();
            gridView1.MoveFirst();
        }
    }
}
